<?php

namespace backend\models;
use common\helps\tools;
use yii\behaviors\TimestampBehavior;
use Yii;
use yii\db\ActiveRecord;
use yii\db\Exception;
/**
 * This is the model class for table "auth_group_access".
 *
 * @property integer $created_at
 * @property integer $updated_at
 */
class AuthGroupAccess extends ActiveRecord
{
    public $auth_access_ids; //新增用户权限字符串

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%auth_group_access}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
         return [
             [['uid','group_role_id'], 'safe'],
             [['auth_access_ids','uid'],'required','message' =>'{attribute}不能为空'],
         ];
    }


    public function scenarios()
    {
        return [
            'default' => [
                'uid',
                'group_role_id',
                'created_at',
                'updated_at',
                'auth_access_ids',
            ],
            'create' => [
                'id',
                'uid',
                'group_role_id',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'auth' => [
                'auth_access_ids',
                'uid',
            ]

            ];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id'=>'自增id',
            'uid' => '会员id',
            'group_role_id' => '角色id',
            'auth_access_ids'=>'新增权限',
        ];
    }

    /**
     * 新增数据
     * @param array $params 新增数据
     * @param  int $id 更新id
     * @author hey_heyang(635870453@qq.com)
     * @return  array|bool|\yii\db\ActiveRecord[]
     */
    public  static function  saveData($params,$id=0){
        $t = static::getDb()->beginTransaction();
        try {
            $auth_group_access = new self();
            $auth_group_access->scenario='create';
            $auth_group_access->setAttributes($params,false);
            if (!$auth_group_access->save()) {
                $t->rollBack();
                return $auth_group_access;
            }
            $auth_group_access->refresh();
            $t->commit();
            return $auth_group_access;
        } catch (Exception $e) {
            $t->rollback();
            return $e;
        }

    }

    /**
     * 新增授权数据
     * @param string $params
     * @param  int $user_id
     * @author hey_heyang(635870453@qq.com)
     * @return  array|bool|\yii\db\ActiveRecord[]
     */
    public  static function  addAccess($params,$user_id){
        $t = static::getDb()->beginTransaction();
        try {
            // 先删除原先权限
            $ag_model = new AuthGroupAccess();
            $ag_model->deleteAll(['uid'=>$user_id]);
            $access_array=explode(',',$params['auth_access_ids']);
            foreach($access_array as $key=>$value){
                $update['uid'] = $user_id;
                $update['group_role_id'] = intval($value);
                $auth_group_access = new self();
                $auth_group_access->scenario = 'create';
                $auth_group_access->setAttributes($update,false);
                if (!$auth_group_access->save()) {
                    $t->rollBack();
                    return $auth_group_access;
                }
            }
            $auth_group_access->refresh();
            $t->commit();
            tools::delAuthCache();
            return $auth_group_access;
        } catch (Exception $e) {
            $t->rollback();
            return $e;
        }

    }

    /**
     * 新增角色授权数据
     * @param string $insert_data
     * @param string $delete_data
     * @param string $role_id
     * @author hey_heyang(635870453@qq.com)
     * @return  array|bool|\yii\db\ActiveRecord[]
     */
    public  function editUserRole($insert_data,$delete_data,$role_id){
        $access_model = new self();
        $model = new AuthGroup();
        if(!$model->find()->where(['id'=>$role_id,'status'=>1])->one()){
            return false;
        }
        $t = static::getDb()->beginTransaction();
        try {
            $data = $access_model->find()->select('uid')->where(['group_role_id' => $role_id])->asArray()->all();
            $user_ids = array_column($data,'uid');
            if (!empty($insert_data)) { //新增数据
                $insert_array = explode(',', $insert_data);
                foreach ($insert_array as $k => $v) {
                    if (!in_array($v, $user_ids)) {
                        $insert[] = ['uid' => $v, 'group_role_id' => $role_id,'created_at'=>time(),'updated_at'=>time()];
                    }
                }
                if (!empty($insert)) {
                    Yii::$app->db->createCommand()->batchInsert('auth_group_access', ['uid', 'group_role_id','created_at','updated_at'], $insert)->execute();
                }
            }
            if (!empty($delete_data)) {
                $delete_array = explode(',', $delete_data);
                foreach ($delete_array as $key => $value) {
                    if (in_array($value, $user_ids)) {
                        $delete[] = $value;
                    }
                }
                if (!empty($delete)) {
                    Yii::$app->db->createCommand()->delete('auth_group_access','uid in'.'('.implode(',',$delete).')')->execute();
            }
            }
            $access_model->refresh();
            $t->commit();
            return true;
        }catch (Exception $e) {
            $t->rollback();
            return false;
        }

    }


}
